<?php
namespace app\controller;

use app\BaseController;
use app\model\ClassInfo;
use app\model\ClassNotice;
use app\model\User;
use app\Request;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\facade\Db;
use think\Filesystem;

class StudentInfoController extends BaseController
{
    /**
     * 查找学生信息
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getStudentInfo(Request $request){
        $uid = $request->user_id;
        //通过获取到的用户id去查找到class_id，并且将它写成一个叫class_id的变量($class_id
        $class_id = User::where('id','=',$uid)->value('class_id');
        //先看下面一行代码 得知我们需要查找很多个字段 所有将他们封装成一个数组变量
        $findInfo = ['id','class_id','student_id','name','sex','phone','email'];
        //运用上面的变量去查找出需要的学生信息
        $student_info = User::Where('class_id','=',$class_id)->field($findInfo)->select();
        return $this->returnJson(self::SUCCESS,'成功',$student_info);
    }

    /**
     * 修改学生信息
     * @param Request $request
     * @return mixed
     */
    public function putStudentInfo(Request $request){
        $data = $request->param(['id','class_name','password','name','sex','phone','email']);
        foreach ($data as $k => $v){

            $cid = ClassInfo::where('class_name','=',$data['class_name'])->value('id');
            $isUpdate = User::where('id','=',$data['id'])->update([
                'class_id'      => $cid,
                'name'          => $data['name'],
                'sex'           => $data['sex'],
                'phone'         => $data['phone'],
                'password'      => $data['password'],
                'email'         => $data['email'],

            ]);
        }
        if ($isUpdate != 1){
            return $this->returnJson(self::SUCCESS,'失败','');
        }
        return $this->returnJson(self::SUCCESS,'成功','');
    }

    /**
     * 添加学生信息
     * @param Request $request
     * @return mixed
     */
    public function postStudentInfo(Request $request){
        $uid = $request->user_id;
        $getData = $request->param(['name','sex','phone','student_id','class_name','email']);
        $cid = ClassInfo::where('class_name','=',$getData['class_name'])->value('id');
        $isSuccess = User::create([
            'class_id'      => $cid,
            'user_id'       => $uid,
            'student_id'    => $getData['student_id'],
            'name'          => $getData['name'],
            'sex'           => $getData['sex'],
            'phone'         => $getData['phone'],
            'email'         => $getData['email'],
            'password'      => 123456,
        ]);
        if (empty($isSuccess)){
            return $this->returnJson(self::SERVER_ERROR,'上传失败','');
        }
        return $this->returnJson(self::SUCCESS,'上传成功','');
    }

    /**
     * 删除学生信息
     * @param Request $request
     * @return mixed
     */
    public function deleteStudentInfo(Request $request){
        $sid = $request->delete('student_id');
        $isDelete = User::where('student_id','=',$sid)->useSoftDelete('delete_time',time())->delete();
        if ($isDelete != 1){
            return $this->returnJson(self::SERVER_ERROR,'删除失败','');
        }
        return $this->returnJson(self::SUCCESS,'删除成功','');
    }

    /**
     * 通过excel批量添加学生信息
     * @param Request $request
     * @return mixed|\think\response\Json
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     */
    public function importData(Request $request){
        // 获取表单上传文件
        $file[] = request()->file('file');
        $savename = \think\facade\Filesystem::putFile('file', $file[0]);
        $fileExtendName = substr(strrchr($savename, '.'), 1);
        // 有Xls和Xlsx格式两种
        if ($fileExtendName == 'xlsx') {
            $objReader = IOFactory::createReader('Xlsx');
        } else {
            $objReader = IOFactory::createReader('Xls');
        }
        $objReader->setReadDataOnly(TRUE);
        // 读取文件，tp6默认上传的文件，在runtime的相应目录下，可根据实际情况自己更改

        $objPHPExcel = $objReader->load(root_path() . '/runtime/storage/' . $savename);
        $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet

        $highestRow = $sheet->getHighestRow();       // 取得总行数
        $highestColumn = $sheet->getHighestColumn();   // 取得总列数
        \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
        $lines = $highestRow - 1;
        if ($lines <= 0) {
            return json(['code' => 0, 'message' => '保存失败']);
        }
        $data = array();
        for ($j = 2; $j <= $highestRow; $j++) {
            $data[$j - 2] = [
                'class_id' => trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue()),
                'head_img' => trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue()),
                'student_id' => trim($objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue()),
                'password' => trim($objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue()),
                'name' => trim($objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue()),
                'sex' => trim($objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue()),
                'phone' => trim($objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue()),
                'email' => trim($objPHPExcel->getActiveSheet()->getCell("H" . $j)->getValue()),
            ];
        }
        $rt = Db::name('user')->insertAll($data);

        if ($rt !== false) {
            return $this->returnJson(self::SUCCESS,'上传成功','');
        } else {
            return $this->returnJson(self::SERVER_ERROR,'上传失败','');
        }
    }
}